package com.example.keyboardedittext.edittext;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.example.keyboardedittext.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gongshuobo on 2016/11/21.
 */

public class LayoutEditText extends LinearLayout {


    private List<EditText> editTextList;//控制输入框

    private List<ImageView> resultImageList;//控制答题卡回显


    private List<LinearLayout> linearLayouts;//整个编辑框


    private int currentClickEdit = 0;//当前编辑框的位置

    private int lastClickEdit = 0;//上个编辑框的位置

    private OnItemEditClick onItemEditClick;//每个编辑框的点击事件


    public LayoutEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        editTextList = new ArrayList<>();
        resultImageList = new ArrayList<>();
        linearLayouts = new ArrayList<>();
    }

    public LayoutEditText(Context context) {
        super(context);
        editTextList = new ArrayList<>();
        resultImageList = new ArrayList<>();
        linearLayouts = new ArrayList<>();
    }


    /**
     * 获取当前布局中点击的EdiText
     */

    public EditText getCurrentEditText() {
        return editTextList.get(currentClickEdit);
    }

    /**
     * 更换下一个EditText
     */

    public void setNextEditText() {
        if (currentClickEdit < editTextList.size() - 1) {
            currentClickEdit++;
            editTextList.get(lastClickEdit).setBackgroundResource(R.drawable.edittext_border);
            lastClickEdit = currentClickEdit;
            //当前点击的编辑框为编辑框数组当前刚刚生成的长度
            editTextList.get(currentClickEdit).setBackgroundResource(R.drawable.edittext_border_pressed);
        }
    }

    /**
     * 更换上一个EditText
     */
    public void setLastEditText() {
        if (currentClickEdit != 0 && currentClickEdit > 0) {
            currentClickEdit--;
            editTextList.get(lastClickEdit).setBackgroundResource(R.drawable.edittext_border);
            lastClickEdit = currentClickEdit;
            //当前点击的编辑框为编辑框数组当前刚刚生成的长度
            editTextList.get(currentClickEdit).setBackgroundResource(R.drawable.edittext_border_pressed);
        }

    }




    /**
     * 生成指定数量的编辑框
     */

    public void signEditText(int count) {
        for (int ia = 0; ia < count; ia++) {
            LinearLayout linearLayout = (LinearLayout) getLayoutView(R.layout.item_question_card_fill);
            TextView textView = (TextView)linearLayout.findViewById(R.id.tv_sort);
            EditText editText = (EditText) linearLayout.findViewById(R.id.edit_fill);
            ImageView imageView = (ImageView)linearLayout.findViewById(R.id.img_result);
            TextView fillTextView = (TextView)linearLayout.findViewById(R.id.tv_info);
            textView.setText("空"+(editTextList.size() + 1)+":");
//            linearLayout.setPadding(10, 10, 10, 10);
//            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
//            TextView textView = new TextView(getContext());
//            textView.setText("空" + (editTextList.size() + 1));
//            textView.setBackgroundColor(getResources().getColor(R.color.black));
//            textView.setGravity(Gravity.CENTER);
//            EditText editText = new EditText(getContext());
//            editText.setFocusable(false);
//            editText.setBackgroundResource(R.drawable.edittext_border);
//            ImageView imageView = new ImageView(getContext());
//            TextView fillTextView = new TextView(getContext());
            final int currentindex = editTextList.size();
            editText.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (onItemEditClick != null) {
                        currentClickEdit = currentindex;
                        editTextList.get(lastClickEdit).setBackgroundResource(R.drawable.edittext_border);
                        lastClickEdit = currentClickEdit;
                        //当前点击的编辑框为编辑框数组当前刚刚生成的长度
                        editTextList.get(currentClickEdit).setBackgroundResource(R.drawable.edittext_border_pressed);
                        onItemEditClick.onItemClick(currentClickEdit);
                    }
                }
            });
//            linearLayout.addView(textView, getWeightParams(0.5f));
//            linearLayout.addView(editText, getWeightParams(2.0f));
//            linearLayout.addView(imageView,getImgParams());
//            linearLayout.addView(fillTextView,getWeightParams(1.0f));
            addView(linearLayout, getKeyBoardNavigationParams());
            editTextList.add(editText);
            resultImageList.add(imageView);
            linearLayouts.add(linearLayout);
        }
    }

    /**
     * 删除指定数量的编辑框
     */

    private void deleteEditText(int count) {
        if(linearLayouts.size()!=0 && editTextList.size()!=0&&resultImageList.size()!=0){
            for (int i = 0; i < count; i++) {
                removeView(linearLayouts.get(linearLayouts.size() - 1));
                linearLayouts.remove(linearLayouts.size() - 1);
                editTextList.remove(editTextList.size() - 1);
                resultImageList.remove(resultImageList.size()-1);
            }
        }
    }


    /**
     * 更换编辑框文本
     */

    public void setLayoutEditText() {
//        if (questionBean == null || questionBean.getLeft() == null) {
//            return;
//        }
//
//        String[] strings = new String[0];
//        if (questionBean.getUserAnswerBeans() != null) {
//            listUserAnswerList = questionBean.getUserAnswerBeans();
//            strings = new String[listUserAnswerList.size()];
//            for (int i = 0; i < listUserAnswerList.size(); i++) {
//                strings[i] = listUserAnswerList.get(i).getRet();
//            }
//            Log.e("aaa","问题"+questionBean.getUserAnswerBeans().toString());
//        }
//        clearAllEditTextText();
//        currentClickEdit = 0;
//        if (questionBean.getLeft().size() == editTextList.size()) {
//            if(editTextList.size()!=0){
//                editTextList.get(lastClickEdit).setBackgroundResource(R.drawable.edittext_border);
//                lastClickEdit = 0;
//            }
//            setEditTextListText(strings);
//        } else if (questionBean.getLeft().size() > editTextList.size()) {
//            if(editTextList.size()!=0){
//                editTextList.get(lastClickEdit).setBackgroundResource(R.drawable.edittext_border);
//                lastClickEdit = 0;
//            }
//            signEditText(questionBean.getLeft().size() - editTextList.size());
//            setEditTextListText(strings);
//        } else if (questionBean.getLeft().size() < editTextList.size()) {
//            if(lastClickEdit<=editTextList.size()){
//                editTextList.get(lastClickEdit).setBackgroundResource(R.drawable.edittext_border);
//                lastClickEdit = 0;
//            }
//            deleteEditText(editTextList.size() - questionBean.getLeft().size());
//            setEditTextListText(strings);
//        }
//        if(editTextList.size()!=0){
//            editTextList.get(currentClickEdit).setBackgroundResource(R.drawable.edittext_border_pressed);
//        }
    }

    /**
     * 设置所有编辑框的文本
     */

    public void setEditTextListText(String[] texts) {
        if(texts==null || texts.length<=0) {
            return;
        }
        for (int i = 0; i < editTextList.size(); i++) {
            editTextList.get(i).setText(texts[i]);
        }
    }

    /**
     * 清空所有编辑框文本
     */

    public void clearAllEditTextText(){
        for(int i=0;i<editTextList.size();i++){
            editTextList.get(i).setText("");
        }
    }

    /**
     * 根据布局id返回一个绘制的view
     **/
    public View getLayoutView(int resourceId) {
        return LayoutInflater.from(getContext()).inflate(resourceId, null);
    }

    /**
     * 每个EditText的布局参数
     *
     * @return
     */
    public RelativeLayout.LayoutParams getKeyBoardNavigationParams() {
        return new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    }

    /**
     * ScrollView线性布局参数
     **/

    public RelativeLayout.LayoutParams getMatchParams() {
        return new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    }

    /**
     * 控件自适应布局
     **/
    public RelativeLayout.LayoutParams getWrapParams() {
        return new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    }

    /**
     * 权重比例布局参数
     */

    public LinearLayout.LayoutParams getWeightParams(float weight) {
        return new LayoutParams(0, LayoutParams.WRAP_CONTENT, weight);
    }

    /**
     * 正确答案固定参数
     */

    public RelativeLayout.LayoutParams getImgParams(){
        return new RelativeLayout.LayoutParams(40,40);
    }



    public void showCorrectAnswer(){
//        if(resultImageList==null || listUserAnswerList==null){
//            return;
//        }
//        if(resultImageList.size()==listUserAnswerList.size()){
//            for(int i=0;i<resultImageList.size();i++){
//                if(listUserAnswerList.get(i).getCor().equals("0")){//未批改
//
//                }else if(listUserAnswerList.get(i).getCor().equals("1")){//错误
//                    resultImageList.get(i).setBackgroundResource(R.drawable.icon_look_homework_error);
//                    editTextList.get(i).setBackgroundColor(getResources().getColor(R.color.result_error));
//                }else if(listUserAnswerList.get(i).getCor().equals("2")){//半对
//                    resultImageList.get(i).setBackgroundResource(R.drawable.btn_homework_bandui);
//                }else if(listUserAnswerList.get(i).getCor().equals("3")){//对
//                    resultImageList.get(i).setBackgroundResource(R.drawable.icon_look_homework_correct);
//                    editTextList.get(i).setBackgroundColor(getResources().getColor(R.color.result_correct));
//                }
//            }
//        }


    }

    public void setOnItemClick(OnItemEditClick onItemEditClick) {
        this.onItemEditClick = onItemEditClick;
    }

    public interface OnItemEditClick {
        void onItemClick(int currentClick);
    }

    public void displayBitmapOnText(Bitmap thumbnailBitmap) {
        SpannableString span = new SpannableString("1");
        if (thumbnailBitmap == null) {
            return;
        }

        int start = getCurrentEditText().getSelectionStart();
        span.setSpan(new ImageSpan(thumbnailBitmap), span.length() - 1, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (getCurrentEditText() != null) {
            Editable et = getCurrentEditText().getText();
            et.insert(start, span);
            getCurrentEditText().setText(et);
            getCurrentEditText().setSelection(start + span.length());
        }
        getCurrentEditText().setLineSpacing(10f, 1f);
    }

    public void showFraction(Bitmap bitmap) {
        ImageSpan imageSpan = new ImageSpan(getContext(), bitmap);
        // 创建一个SpannableString对象，以便插入用ImageSpan对象封装的图像
        String tempUrl = "加载中...";
        SpannableString spannableString = new SpannableString(tempUrl);
        // 用ImageSpan对象替换你指定的字符串
        spannableString.setSpan(imageSpan, 0, tempUrl.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 将选择的图片追加到EditText中光标所在位置
        int index = getCurrentEditText().getSelectionStart(); // 获取光标所在位置
        Editable edit_text = getCurrentEditText().getEditableText();
        if (index < 0 || index >= edit_text.length()) {
            edit_text.append(spannableString);
        } else {
            edit_text.insert(index, spannableString);
        }
        System.out.println("插入的图片：" + spannableString.toString());
    }

    public void deleteEditTextSpan() {
        Spanned s = getCurrentEditText().getEditableText();
        ImageSpan[] imageSpan = s.getSpans(0, s.length(), ImageSpan.class);
        for (int i = imageSpan.length - 1; i >= 0; i--) {
            if (i == imageSpan.length - 1) {
                int start = s.getSpanStart(imageSpan[i]);
                int end = s.getSpanEnd(imageSpan[i]);
                Editable et = getCurrentEditText().getText();
                et.delete(start, end);
            }
        }
        getCurrentEditText().invalidate();
    }

    /**
     * 是否有ImageSpan
     */

    public void isTextSpan(){

    }


}
